package Singleton;

import java.util.HashMap;
import java.util.Map;

//单例模式拓展
public class ThreeSingleton {
    private final static String DEFAULT_PREKEY = "cache";//为后面的key定义前缀
    private static Map<String,ThreeSingleton>
    map = new HashMap<String, ThreeSingleton>();//定义缓存实例的容器
    private static int number = 1;//定义初始化实例的数目为1
    private final static int NUM_MAX=3;//定义最大数目
    private ThreeSingleton(){
        System.out.println("threesingleton create");
    }
    public static synchronized ThreeSingleton getInstance(){
        //通过缓存理念及方式控制数量
        String key = DEFAULT_PREKEY+number;
        ThreeSingleton threeSingleton = map.get(key);//获取
        if(threeSingleton == null){
            threeSingleton = new ThreeSingleton();
            map.put(key,threeSingleton);
        }
        //实例数量加一
        number++;
        if (number>NUM_MAX){
            number = 1;
        }
        //返回对象
        return threeSingleton;
    }
    public static void main(String[] args) {
        //实例
        ThreeSingleton ts1 = getInstance();
        ThreeSingleton ts2 = getInstance();
        ThreeSingleton ts3 = getInstance();
        ThreeSingleton ts4 = getInstance();
        ThreeSingleton ts5 = getInstance();
        ThreeSingleton ts6 = getInstance();
        System.out.println(ts1.toString());
        System.out.println(ts2.toString());
        System.out.println(ts3.toString());
        System.out.println(ts4.toString());
        System.out.println(ts5.toString());
        System.out.println(ts6.toString());
    }
}
